package org.minuframework.utils;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.minuframework.core.ApplicationConfigurer;
import org.minuframework.encrypt.AesUtils;
import org.minuframework.encrypt.UrlUtils;
import org.minuframework.exception.ExceptionFailed;
import org.minuframework.lang.StringUtils;
import org.minuframework.net.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.common.collect.Maps;

public class ParamUtils {

    public static final String DEFAULT_BASE64_SUFFIX = "imgstr";

    // ------------------------------------------------------------------------

    // ------------------------------------------------------------------------

    /**
     * 获取参数
     * 
     * @param request HttpServletRequest
     * @return HashMap<String, Object>
     */
    public static HashMap<String, Object> getParamMap(HttpServletRequest request) {
        HashMap<String, Object> paramMap = Maps.newHashMap();

        Map<String, String[]> params = request.getParameterMap();
        Set<String> it = params.keySet();
        for (String key : it) {
            String[] str2 = params.get(key);
            paramMap.put(key, str2[0]);
        }
        paramMap.putAll(getLocaleMap(request));

        return paramMap;
    }

    /**
     * 获取参数（文件上传使用）
     * 
     * @param request HttpServletRequest
     * @return HashMap<String, Object>
     */
    public static HashMap<String, Object> getMultipartParamMap(HttpServletRequest request) {
        HashMap<String, Object> paramMap = Maps.newHashMap();

        MultipartHttpServletRequest multipartHttpServletRequest =
                (MultipartHttpServletRequest) request;
        Map<String, String[]> params = multipartHttpServletRequest.getParameterMap();
        Set<String> it = params.keySet();
        for (String key : it) {
            String[] str2 = params.get(key);
            paramMap.put(key, str2[0]);
        }
        paramMap.putAll(getLocaleMap(request));

        return paramMap;
    }

    /**
     * 获取 Locale 参数
     * 
     * @param request HttpServletRequest
     * @return HashMap<String, Object>
     */
    public static HashMap<String, Object> getLocaleMap(HttpServletRequest request) {
        HashMap<String, Object> paramMap = Maps.newHashMap();

        paramMap.put("ip", LocaleUitls.getIp(request));
        Locale locale = request.getLocale();
        paramMap.put("country", locale.getCountry());
        paramMap.put("language", locale.getLanguage());
        paramMap.put("script", locale.getScript());
        paramMap.put("variant", locale.getVariant());
        paramMap.put("displayCountry", locale.getDisplayCountry());
        paramMap.put("displayLanguage", locale.getDisplayLanguage());
        paramMap.put("displayName", locale.getDisplayName());
        paramMap.put("displayScript", locale.getDisplayScript());
        paramMap.put("displayVariant", locale.getDisplayVariant());

        return paramMap;
    }

    /**
     * 获取参数
     * 
     * @param request HttpServletRequest
     * @param helper boolean true → pageSize，pageSize 转 dayNum，daySize
     * @return HashMap<String, Object>
     */
    public static HashMap<String, Object> getParamMap(HttpServletRequest request, boolean helper) {
        HashMap<String, Object> paramMap = getParamMap(request);

        HashMap<String, Object> currentPage = getCurrentDay(paramMap);
        if (currentPage.containsKey("dayNum")) {
            int param = Integer.parseInt(currentPage.get("dayNum").toString());
            paramMap.put("dayNum", param);
            paramMap.remove("pageNum");
        }
        if (currentPage.containsKey("daySize")) {
            int param = Integer.parseInt(currentPage.get("daySize").toString());
            paramMap.put("daySize", param);
            paramMap.remove("pageSize");
        }

        return paramMap;
    }

    /**
     * 获取参数
     * 
     * @param request HttpServletRequest
     * @param encryptKey 解密key
     * @return 参数 params
     */
    public static HashMap<String, Object> getParamMap(HttpServletRequest request,
            String decryptKey) {
        HashMap<String, Object> paramMap = Maps.newHashMap();

        Map<String, String[]> params = request.getParameterMap();
        Set<String> it = params.keySet();
        for (String key : it) {
            String[] str2 = params.get(key);
            String encryptStr = str2[0];
            try {
                paramMap.put(key, AesUtils.aesDecrypt(encryptStr, decryptKey));
            } catch (Exception e) {
                paramMap.put(key, encryptStr);
            }
        }
        paramMap.putAll(getLocaleMap(request));

        return paramMap;
    }

    /**
     * 获取参数
     * 
     * @param request HttpServletRequest
     * @param encryptKey 解密key
     * @param helper boolean true → pageSize，pageSize 转 dayNum，daySize
     * @return 参数 HashMap<String, Object>
     */
    public static HashMap<String, Object> getParamMap(HttpServletRequest request, String decryptKey,
            boolean helper) {
        HashMap<String, Object> paramMap = getParamMap(request, decryptKey);

        HashMap<String, Object> currentPage = getCurrentDay(paramMap);
        if (currentPage.containsKey("dayNum")) {
            int param = Integer.parseInt(currentPage.get("dayNum").toString());
            paramMap.put("dayNum", param);
            // paramMap.remove("pageNum");
        }
        if (currentPage.containsKey("daySize")) {
            int param = Integer.parseInt(currentPage.get("daySize").toString());
            paramMap.put("daySize", param);
            // paramMap.remove("pageSize");
        }

        return paramMap;
    }

    // ------------------------------------------------------------------------

    // ------------------------------------------------------------------------

    /**
     * 获取参数 pageSize，pageSize 转 dayNum，daySize
     * 
     * @param params Map<String, Object>
     * @return HashMap<String, Object>
     */
    public static HashMap<String, Object> getCurrentDay(Map<String, Object> params) {
        HashMap<String, Object> paramMap = Maps.newHashMap();

        int pageNum = 0, pageSize = 0;
        if (params.containsKey("pageNum")) {
            pageNum = Integer.parseInt(params.get("pageNum").toString());
            pageNum = pageNum <= 0 ? 1 : pageNum;
        }
        if (params.containsKey("pageSize")) {
            pageSize = Integer.parseInt(params.get("pageSize").toString());
            pageSize = pageNum <= 0 ? 15 : pageSize;
        }

        int dayNum = pageNum == 1 ? 0 : (pageNum - 1) * pageSize + 1;
        paramMap.put("dayNum", dayNum);

        int daySize = pageNum * pageSize;
        paramMap.put("daySize", daySize);

        return paramMap;
    }

    /**
     * 获取参数字符串（http请求）
     * 
     * @param params 参数 Map<String, Object>
     * @return String
     */
    public static String getParamSTR(Map<String, Object> params) {
        StringBuilder param = new StringBuilder();
        if (params != null) {
            for (Entry<String, Object> entry : params.entrySet()) {
                if (param.length() > 0) {
                    param.append("&");
                }
                param.append(entry.getKey());
                param.append("=");
                param.append(entry.getValue());
            }
        }
        return param.toString();
    }

    /**
     * 获取参数字符串（http请求）
     * 
     * @param params 参数 Map<String, Object>
     * @param method RequestMethod
     * @return String
     */
    public static String getParamSTR(Map<String, Object> params,
            org.springframework.web.bind.annotation.RequestMethod method) {
        StringBuilder param = new StringBuilder();
        if (params != null) {
            for (Entry<String, Object> entry : params.entrySet()) {
                if (param.length() == 0) {
                    if (method == org.springframework.web.bind.annotation.RequestMethod.GET) {
                        param.append("?");
                    }
                } else if (param.length() > 0) {
                    param.append("&");
                }
                param.append(entry.getKey());
                param.append("=");
                param.append(entry.getValue());
            }
        }
        return param.toString();
    }

    /**
     * 获取参数字符串（http请求）
     * 
     * @param params 参数 Map<String, Object>
     * @param method RequestMethod
     * @return String
     */
    public static String getParamSTR(Map<String, Object> params, RequestMethod method) {
        StringBuilder param = new StringBuilder();
        if (params != null) {
            for (Entry<String, Object> entry : params.entrySet()) {
                if (param.length() == 0) {
                    if (method == RequestMethod.GET) {
                        param.append("?");
                    }
                } else if (param.length() > 0) {
                    param.append("&");
                }
                param.append(entry.getKey());
                param.append("=");
                param.append(entry.getValue());
            }
        }
        return param.toString();
    }

    /**
     * 获取参数字符编码
     * 
     * @param word 参数
     * @return 字符编码
     */
    public static Charset getParamCharset(String word) {
        String charset = null;
        if (!StringUtils.isEmpty(word)) {
            try {
                if (word.equals(new String(word.getBytes("GB2312"), "GB2312"))) {
                    charset = "GB2312";
                } else if (word.equals(new String(word.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
                    charset = "ISO-8859-1";
                } else if (word.equals(new String(word.getBytes("UTF-8"), "UTF-8"))) {
                    charset = "UTF-8";
                } else if (word.equals(new String(word.getBytes("GBK"), "GBK"))) {
                    charset = "GBK";
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return !StringUtils.isEmpty(charset) ? Charset.forName(charset) : null;
    }

    /**
     * 获取文件后缀名
     * 
     * @param name 文件名
     * @return 文件后缀名
     */
    public static String suffix(String name) {
        String result = null;
        if (StringUtils.isNotEmpty(name)) {
            result = name.substring(name.lastIndexOf("."), name.length());
        }
        return result;
    }

    /**
     * 获取文件真实路径
     * 
     * @param name 文件名
     * @return 文件真实路径 URL
     * @throws ExceptionFailed 抛出异常
     */
    public static String getPathName(String name) {
        StringBuilder result = new StringBuilder();
        URL url = Thread.currentThread().getContextClassLoader().getResource(name);
        String param = url.getFile();
        try {
            result.append(UrlUtils.urlDencoder(param, ApplicationConfigurer.DEFAULE_MINU_CHARSET));
        } catch (UnsupportedEncodingException e) {
        }
        return result.toString();
    }

}
